//
//  BaseModel.m
//  Pods
//
//  Created by Sheng long on 16/7/4.
//
//

#import "BaseModel.h"
#import <LKDBHelper/LKDBHelper.h>
#import <objc/runtime.h>
#import "CommUtls+Object.h"

@implementation BaseModel

- (void)dealloc {
#ifdef DBUG
    NSLog(@"dealloc -- %@",self.class);
#endif
}

#pragma mark - LKDBHelper
+ (LKDBHelper *)getUsingLKDBHelper {
    static LKDBHelper *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filePath = [LKDBUtils getPathForDocuments:@"PhoneApp.db"];
        sharedInstance = [[LKDBHelper alloc] initWithDBPath:filePath];
    });
    return sharedInstance;
}

+ (NSDictionary *)getTableMapping {
    NSCAssert([self tableMapping] != nil, @"BaseModel Error:tableMapping未实现");
    return [self tableMapping];
}

+ (NSDictionary *)tableMapping {
    return nil;
}

#pragma mark - MTLJSONSerializing
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    //对象名称在前，转换的数据在后
    return @{
             
             };
}

/**
 *  当服务端返回NSNull转基础数据类型时容错
 */
- (void)setNilValueForKey:(NSString *)key {
    [self setValue:@0 forKey:key];  // For NSInteger/CGFloat/BOOL
}

/**
 *  当服务端返回基础数据类型时，定义的属性是NSString类型的转换
 *  NSNumber--NSString
 */
- (void)setValue:(id)value forKey:(NSString *)key {
    if ([value isKindOfClass:[NSNumber class]]) {
        objc_property_t property = class_getProperty([self class], [key UTF8String]);
//    const char * name = property_getName(property);//获取属性名字
        const char * attributes = property_getAttributes(property);//获取属性类型
        NSString *type = [NSString stringWithUTF8String:attributes];
        if ([type rangeOfString:@"NSString"].location!=NSNotFound) {
            [super setValue:[NSString stringWithFormat:@"%@",value] forKey:key];
            return;
        }
    }
    [super setValue:value forKey:key];
}

+ (NSArray *)modelsFromArray:(NSArray *)array {
    if ((array != nil && ![array isEqual:[NSNull null]])) {
        if (array.count) {
            return [MTLJSONAdapter modelsOfClass:[self class] fromJSONArray:array error:nil];
        }
    }
    return nil;
}

+ (id)modelFromDictionary:(NSDictionary *)dictionary {
    if ((dictionary != nil && ![dictionary isEqual:[NSNull null]])) {
        if (dictionary.count) {
            return [MTLJSONAdapter modelOfClass:[self class] fromJSONDictionary:dictionary error:nil];
        }
    }
    return nil;
}

+ (id)properties_aps {
    return [CommUtls objectProperties:self];
}

@end

